package com.e2j.lib;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Excel数据配置文件加载核心类
 * （建议本类放置到单例内或把本类改成单例使用）
 * 使用方式：
 *   excelLib = new ExcelLib();
 *   excelLib.load();
 *   LibXXXX libXXXX = excelLib.libData().xxxxMap(索引参数);
 * @author 杨永良
 * @date 2022/7/13 9:22
 **/
public class ExcelLib {
    static final Logger logger = (Logger) LoggerFactory.getLogger(ExcelLib.class);

    /**
     * 单例，volatile禁止指令重排
     * (防止多线程时非创建线程抢占到cpu，然后发现instance!=null，然后直接返回使用，就会发现instance为空，就会出现异常。)
     */
    private static volatile ExcelLib instance = null;

    /**
     * 获取单例 (DCL模式)
     * @return
     */
    public static ExcelLib getInstance(){
        //双端检锁机制：DCL(Double Check Lock)
        //第一层检查是为了创建后访问不需要线程同步，减少阻塞
        if(instance==null){
            //创建期间保证线程同步,在同一时间内执行下面代码的唯一性
            synchronized (ExcelLib.class){
                if(instance==null){
                    instance = new ExcelLib();
                }
            }
        }
        return instance;
    }

    private ExcelLibData libData;
    private ExcelLibReader libReader;

    /**
     * 是否正常读入配置文件
     */
    private boolean loadedDefinition = false;

    public ExcelLib() {
        libReader = new ExcelLibReader();
        libData = new ExcelLibData();
        //定义可加载文件一定要首次读取
        reloadDefinition();
    }

    public boolean reloadDefinition(){
        loadedDefinition = getLibReader().loadDefinition();
        return loadedDefinition;
    }



    public boolean loadAllFromFile() throws Exception {
        if(!loadedDefinition){
            throw new Exception("Can't not load Definition!");
        }
        return getLibReader().loadFromFileAll(libData);
    }

    public int loadFromGroup(String gruopName) throws Exception {
        if(!loadedDefinition){
            throw new Exception("Can't not load Definition!");
        }
        return getLibReader().loadFromGroup(libData, gruopName);
    }

    public int loadFromFileByName(String dataFullName, boolean isLoadRelations) throws Exception {
        if(!loadedDefinition){
            throw new Exception("Can't not load Definition!");
        }
        return getLibReader().loadFromFileByName(libData, dataFullName, isLoadRelations);
    }


    public ExcelLibReader getLibReader() {
        return libReader;
    }

    public ExcelLibData data(){
        return libData;
    }
}
